package com.dd.ent.car.service.user;

import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.dd.ent.car.AppContext;
import com.dd.ent.car.common.bean.User;
import com.dd.ent.car.common.config.UIConfig;
import com.dd.ent.car.common.config.UrlConfig;
import com.dd.ent.car.common.dao.UserDao;
import com.dd.ent.car.common.vo.UserVo;
import com.dd.ent.car.service.BaseService;
import com.google.gson.reflect.TypeToken;
import com.pp.ent.base.log.MLog;
import com.pp.ent.core.manage.ServiceHandler;
import com.pp.ent.db.DbResult;
import com.pp.ent.view.annotation.Inject;

import org.json.JSONObject;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by spring on 2017/3/16.
 */

public class UserService extends BaseService {
    @Inject
    private UserDao userDao;
    private User user;

    public boolean isLogin() {
        return user == null ? false : true;
    }

    public void refreshUser(User user) {
        this.user = user;
    }

    public void updateUserToDb() {
        userDao.insertUser(user);
    }

    public String getUid() {
        if (isLogin()) {
            return user.getUid();
        }
        return null;
    }

    public User getUser() {
        return user;
    }

    public String getAvathor() {
        return user == null ? "" : user.getAvathor();
    }

    public void loginFromDb() {
        userDao.query(userDao.getQueryBuiler(), "query_db_user");
    }

    public void register(String phoneNumber, String password) {
        Map<String, String> parms = new HashMap<>();
        parms.put("phoneNumber", phoneNumber);
        parms.put("password", password);
        post(UrlConfig.USER_REGISTER, parms, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                MLog.debug(TAG, "register onResponse response=" + response);
                UserVo userVo = AppContext.createGson().fromJson(response.toString(), new TypeToken<UserVo>() {
                }.getType());

                refreshUser(userVo.user);
                userDao.insertUser(userVo.user);
                notifyUI(UIConfig.PHONE_NUMBER_REGISTER_SUCCESS, userVo.user);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                MLog.error(TAG, error);
            }
        });
    }


    public void login(String phoneNumber, String password) {
        Map<String, String> parms = new HashMap<>();
        parms.put("phoneNumber", phoneNumber);
        parms.put("password", password);
        post(UrlConfig.USER_LOGIN, parms, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                MLog.debug(TAG, "register onResponse response=" + response);
                UserVo userVo = AppContext.createGson().fromJson(response.toString(), new TypeToken<UserVo>() {
                }.getType());
                if (userVo == null || !userVo.isSuccess()) {
                    notifyUI(UIConfig.PHONE_NUMBER_LOGIN_FAIL);
                    return;
                }
                refreshUser(userVo.user);
                userDao.insertUser(userVo.user);
                notifyUI(UIConfig.PHONE_NUMBER_LOGIN_SUCCESS, userVo.user);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                MLog.error(TAG, error);
                notifyUI(UIConfig.PHONE_NUMBER_LOGIN_FAIL);
            }
        });
    }

    public void update() {
        Map<String, String> parms = new HashMap<>();
        parms.put("uid", String.valueOf(getUid()));
        parms.put("userName", user.getUserName());
        parms.put("sex", user.getSex());
        parms.put("avathor", user.getAvathor());
        post(UrlConfig.USER_UPDATE_NAME_SEX, parms, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                MLog.debug(TAG, "register onResponse response=" + response);
                updateUserToDb();
                notifyUI(UIConfig.UPDATE_NAME_SEX_SUCCESS);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                MLog.error(TAG, error);
            }
        });
    }


    public void loginOut() {
        if (isLogin()) {
            userDao.delete(getUser(), "login_out_response");
        } else {
            notifyUI(UIConfig.NOTIFY_LOGIN_OUT_SUCCESS);
        }

    }

    /**
     * 找回密码
     *
     * @param phoneNumber
     */
    public void findPassword(String phoneNumber) {
        MLog.info(TAG, "findPassword phoneNumber=" + phoneNumber);
        Map<String, String> parms = new HashMap<>();
        parms.put("phoneNumber", phoneNumber);
        post(UrlConfig.USER_FIND_PASSWORD, parms, new Response.Listener<JSONObject>() {
            @Override
            public void onResponse(JSONObject response) {
                MLog.debug(TAG, "findPassword onResponse response=" + response);
                UserVo userVo = AppContext.createGson().fromJson(response.toString(), new TypeToken<UserVo>() {
                }.getType());
                if (userVo == null || !userVo.isSuccess()) {
                    notifyUI(UIConfig.FIND_PASSWORD_FAIL);
                    return;
                }
                notifyUI(UIConfig.FIND_PASSWORD_SUCCESS, userVo.user);
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                MLog.error(TAG, error);
                notifyUI(UIConfig.FIND_PASSWORD_FAIL);
            }
        });
    }

    @ServiceHandler("login_out_response")
    public void loginOutResopnse(DbResult dbResult) {
        if (dbResult == null || !dbResult.isSuccessful()) {
            notifyUI(UIConfig.NOTIFY_LOGIN_OUT_FAIL);
            return;

        }
        refreshUser(null);
        notifyUI(UIConfig.NOTIFY_LOGIN_OUT_SUCCESS);
    }

    @ServiceHandler("query_db_user")
    public void queryDbUserResponse(DbResult dbResult) {
        if (dbResult == null) {
            return;
        }
        List<User> users = (List<User>) dbResult.data;
        if (users != null && users.size() != 0) {
            refreshUser(users.get(0));
        }
    }


}
